﻿using System.Collections.ObjectModel;
using System.Linq;
using InseSoft.Models.Entities;
using Ninject;

namespace InseSoft.ViewModels
{
    public class CatalogEntityViewModel<T> : EntityViewModel<T>, ICatalogEntityViewModel where T : class
    {
        #region Properties
        
        [Inject]
        public ICatalogSearchViewModel CatalogSearchViewModel { get; set; }

        [Inject]
        public ApplicationSession Session { get; set; }

        #endregion

        #region Methods

        public override void Initialize()
        {
            CatalogSearchViewModel.LoadRecordList(GetList());
            base.Initialize();
        }

        protected override bool NewCanExecute()
        {
            return CatalogSearchViewModel.RecordList.All(i => i.Id != 0);
        }

        protected override void NewExecute()
        {
            base.NewExecute();
            if (typeof(T) != typeof(Empresa))
                DbContext.Set<Empresa>().Attach(Session.Empresa);
        }

        private ObservableCollection<CatalogEntity> GetList()
        {
            var collection = new ObservableCollection<CatalogEntity>();
            foreach (var newEntity in Enumerable.OfType<CatalogEntity>(Entities))
            {
                newEntity.ConfigureValidationRules();
                collection.Add(newEntity);
            }
            return collection;
        }
        
        #endregion
    }
}
